package main

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/url"
	"sort"
	"strings"
)

func main() {
	a11 := "aaaa"
	fmt.Println(a11[:])

	GenMd5("hehe")
	ret := strToMd5("hehe")
	fmt.Println(ret)

	c1 := "hehe"
	c2 := []byte(c1)
	fmt.Println("c2=", c2)

	c3 := fmt.Sprintf("%x", c2)
	fmt.Println("c3=", c3)

	c4 := string(c2)
	fmt.Println("c4=", c4)
	//return

	b1 := map[string]string{}
	b1["a"] = "b"
	b1["c"] = "c d"
	b1["b"] = "e"
	makeSign(b1)

	h := map[string]int{}
	h["foo"] = 1
	fmt.Println(h)

	g := []int{1, 2, 3, 4, 5, 6}
	g = append(g, 7, 8)
	fmt.Println("g=", g)

	//通过make创建切片，指定切片长度
	s := make([]int, 5)
	s[0] = 1
	s[1] = 2
	s[2] = 3
	s[3] = 4
	//通过append往切片里添加数据
	//切片是存储在堆区，数组是存储在栈区
	s = append(s, 4, 6, 7, 8)
	fmt.Println("s=", s)
	fmt.Println("s长度=", len(s))
	//容量一定是>=长度的
	//如果整体数据没有超过1024字节，每次扩展为上次的2倍,超过1024,每次扩展上一次的1/4倍
	fmt.Println("s容量=", cap(s))

	a := make([]interface{}, 5)
	a[0] = "foo"
	a[1] = 1
	a[2] = true
	a = append(a, "bar") //append只能在切片长度之外添加，即使之前切片没有满
	fmt.Println("a=", a)

	b := []int{1, 2, 3}
	fmt.Println("b=", b)

	c := make(map[string]string, 5)
	c["foo"] = "bar"
	c["name"] = "mike"
	c["age"] = "18"
	fmt.Println("c=", c)
	f, _ := json.Marshal(c)
	fmt.Println("f=", string(f))

	//通过make创建map
	d := make(map[string]interface{}, 5)
	d["name"] = "mike"
	d["age"] = 19
	d["test"] = "20"
	fmt.Println("d=", d)
	e, _ := json.Marshal(d)
	var a1 = string(e)

	fmt.Println("e=", string(e))

	fmt.Println([]byte(a1))
}

func makeSign(b1 map[string]string) string {

	slice := []string{}
	for k, _ := range b1 {
		slice = append(slice, k)
	}
	sort.Strings(slice)

	str := ""
	for _, v := range slice {
		str += v + "=" + url.PathEscape(b1[v]) + "&"
	}

	str = strings.Trim(str, "&")
	fmt.Println(str)

	sign := MD5(str)
	fmt.Println("sign=", sign)

	sign1 := strToMd5(str)
	fmt.Println("sign1=", sign1)
	return sign
}

// 生成32位MD5
func MD5(text string) string {
	ctx := md5.New()
	ctx.Write([]byte(text))
	return hex.EncodeToString(ctx.Sum(nil))
}

func strToMd5(text string) string {
	data := []byte(text)
	has := md5.Sum(data)
	//fmt.Println(has)
	md5Str := fmt.Sprintf("%x", has) //将[]byte转为16进制
	return md5Str
}

func GenMd5(text string) {
	h := md5.New()
	h.Write([]byte(text))
	m := h.Sum(nil)
	fmt.Println(base64.StdEncoding.EncodeToString(m))
}
